package demo.hdz.mediacodecdecode.filter;

import android.content.Context;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;

import java.nio.FloatBuffer;

/**
 * @author hdz
 * @date 2022/05/29 11:43
 */
public class DefaultFilter extends BaseFilter {

    //每行前两个值为顶点坐标，后两个为纹理坐标
    private static final float[] VERTEX_DATA = {
            1f, 1f, 1f, 1f,
            -1f, 1f, 0f, 1f,
            -1f, -1f, 0f, 0f,
            1f, 1f, 1f, 1f,
            -1f, -1f, 0f, 0f,
            1f, -1f, 1f, 0f
    };

    private final int[] mFBOIds = new int[1];
    private FloatBuffer mDataBuffer;
    private int aPositionLocation = -1;
    private int aTextureCoordLocation = -1;
    private int uTextureMatrixLocation = -1;
    private int uTextureSamplerLocation = -1;

    public DefaultFilter(Context context) {
        super(context, "shader/v_default.frag", "shader/f_default.frag");
    }

    @Override
    public void init() {
        mDataBuffer = createBuffer(VERTEX_DATA);
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vShader.trim());
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fShader.trim());
        int mShaderProgram = linkProgram(vertexShader, fragmentShader);

        aPositionLocation = GLES20.glGetAttribLocation(mShaderProgram, "aPosition");
        aTextureCoordLocation = GLES20.glGetAttribLocation(mShaderProgram, "aTextureCoordinate");
        uTextureMatrixLocation = GLES20.glGetUniformLocation(mShaderProgram, "uTextureMatrix");
        uTextureSamplerLocation = GLES20.glGetUniformLocation(mShaderProgram, "uTextureSampler");

        GLES20.glGenFramebuffers(1, mFBOIds, 0);
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, mFBOIds[0]);
    }

    @Override
    public void drawFrame(int textureId, float[] transformMatrix) {
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        //会报警告：bindTextureImage: clearing GL error: 0x500
        //GLES20.glActiveTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES);
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);
        GLES20.glUniform1i(uTextureSamplerLocation, 0);
        GLES20.glUniformMatrix4fv(uTextureMatrixLocation, 1, false, transformMatrix, 0);

        if (mDataBuffer != null) {
            mDataBuffer.position(0);
            GLES20.glEnableVertexAttribArray(aPositionLocation);
            GLES20.glVertexAttribPointer(aPositionLocation, 2, GLES20.GL_FLOAT, false, 16, mDataBuffer);

            mDataBuffer.position(2);
            GLES20.glEnableVertexAttribArray(aTextureCoordLocation);
            GLES20.glVertexAttribPointer(aTextureCoordLocation, 2, GLES20.GL_FLOAT, false, 16, mDataBuffer);
        }

        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6);
        GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
    }

    @Override
    public void release() {

    }
}
